<template>
  <el-main class="editor-main">
    <div class="editor-container">
      <!-- 页面标题和操作 -->
      <div class="page-header mb-6">
        <div class="header-text">
          <h2 class="page-title">编辑简历</h2>
          <p class="page-desc">左侧填写信息，右侧实时预览「{{ resumeStore.currentTemplate?.name || '默认模板' }}」效果</p>
        </div>

         <div class="header-actions">
           <el-button class="action-btn download-btn" @click="downloadPDF" type="primary">下载PDF</el-button>
           <el-button class="action-btn save-btn" @click="saveResume" type="success">保存</el-button>
         </div>
      </div>
      
      <el-row :gutter="24" class="main-content">
        <!-- 左侧：模板选择器 -->
        <el-col :span="4" class="template-column">
          <div class="template-selector">
            <div class="template-selector-header">
              <h3>选择模板</h3>
              <p class="template-desc">选择适合的模板风格</p>
            </div>
            
            <div class="template-list">
              <div 
                v-for="tpl in allTemplates" 
                :key="tpl.id"
                class="template-card"
                :class="{ active: resumeStore.selectedTemplateId === tpl.id }"
                @click="resumeStore.loadTemplate(tpl.id)"
              >
                <div class="template-preview" :style="getTemplatePreviewStyle(tpl)">
                  <div class="template-name">{{ tpl.name }}</div>
                  <div class="template-sample">
                    <div class="sample-header" :style="{ backgroundColor: tpl.style.base.primaryColor }"></div>
                    <div class="sample-content">
                      <div class="sample-line" :style="{ backgroundColor: tpl.style.base.primaryColor }"></div>
                      <div class="sample-line short" :style="{ backgroundColor: tpl.style.base.secondaryColor }"></div>
                      <div class="sample-line" :style="{ backgroundColor: tpl.style.base.secondaryColor }"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 中间：编辑区域 -->
        <el-col :span="9" class="edit-column">
          <el-card class="edit-card">
            <el-tabs v-model="activeTab" class="edit-tabs">
              <!-- 基本信息 -->
              <el-tab-pane label="基本信息" name="basic">
                <el-form 
                  label-width="90px" 
                  :model="resumeStore.form" 
                  :rules="formRules"
                  ref="basicFormRef"
                  class="resume-form"
                >
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="姓名" prop="name" class="form-item">
                        <el-input v-model="resumeStore.form.name" placeholder="请输入姓名" class="form-input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="性别" class="form-item">
                        <el-select v-model="resumeStore.form.gender" placeholder="请选择" class="form-select">
                          <el-option label="男" value="male">男</el-option>
                          <el-option label="女" value="female">女</el-option>
                          <el-option label="保密" value="secret">保密</el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="电话" prop="phone" class="form-item">
                        <el-input v-model="resumeStore.form.phone" placeholder="请输入手机号码" class="form-input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="邮箱" prop="email" class="form-item">
                        <el-input v-model="resumeStore.form.email" type="email" placeholder="请输入邮箱地址" class="form-input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="求职意向" prop="intention" class="form-item">
                        <el-input v-model="resumeStore.form.intention" placeholder="请输入求职意向（如：前端开发工程师）" class="form-input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="个人简介" prop="intro" class="form-item">
                        <el-input 
                          v-model="resumeStore.form.intro" 
                          type="textarea" 
                          :rows="4" 
                          placeholder="请简要介绍自己的技能、经验和个人特点" 
                          class="form-input" 
                        />
                      </el-form-item>
                    </el-col>
                    <!-- 照片上传（始终显示） -->
                    <el-col :span="24">
                      <el-form-item label="简历照片" class="form-item">
                        <div class="photo-upload-container">
                          <!-- 照片预览区域 -->
                          <div class="photo-preview" v-if="resumeStore.form.photoUrl">
                            <img :src="getPhotoSrc(resumeStore.form.photoUrl)" alt="简历照片" class="preview-image" />
                            <div class="photo-actions">
                              <el-button size="small" type="danger" @click="removePhoto">删除照片</el-button>
                            </div>
                          </div>
                          
                          <!-- 上传按钮 -->
                          <el-upload
                            v-else
                            class="photo-upload"
                            action="#"
                            :show-file-list="false"
                            :before-upload="beforeUploadPhoto"
                            accept="image/jpeg,image/png,image/webp"
                            drag
                          >
                            <div class="upload-area">
                              <el-icon class="upload-icon"><Upload /></el-icon>
                              <div class="upload-text">
                                <p>点击或拖拽上传照片</p>
                                <p class="upload-tip">支持 JPG、PNG、WebP 格式，建议尺寸 {{ resumeStore.currentTemplate?.style.photo.width || 120 }}×{{ resumeStore.currentTemplate?.style.photo.height || 120 }}px</p>
                              </div>
                            </div>
                          </el-upload>
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-tab-pane>

               <!-- 教育经历 -->
               <el-tab-pane label="教育经历" name="education">
                 <div class="section-content">
                   <!-- 教育经历数量提示 -->
                   <div v-if="resumeStore.educationList.length > 3" class="limit-warning">
                     <el-alert
                       title="提示"
                       type="warning"
                       :closable="false"
                       show-icon
                     >
                       <template #default>
                         <p>教育经历超过3个，PDF预览将只显示前3个。建议保留最重要的教育经历。</p>
                       </template>
                     </el-alert>
                   </div>
                   
                   <div v-for="(item, index) in resumeStore.educationList" :key="index" class="education-item">
                    <el-form label-width="90px" class="resume-form">
                      <el-row :gutter="24">
                        <el-col :span="12">
                          <el-form-item label="学校" class="form-item">
                            <el-input v-model="item.school" placeholder="请输入学校名称" class="form-input" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="专业" class="form-item">
                            <el-input v-model="item.major" placeholder="请输入专业" class="form-input" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="11">
                          <el-form-item label="开始时间" class="form-item">
                            <el-date-picker 
                              v-model="item.startDate" 
                              type="month" 
                              placeholder="选择开始时间" 
                              class="form-input"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="11">
                          <el-form-item label="结束时间" class="form-item">
                            <el-date-picker 
                              v-model="item.endDate" 
                              type="month" 
                              placeholder="选择结束时间" 
                              class="form-input"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="2" class="delete-col">
                          <el-button 
                            :icon="Delete" 
                            size="small" 
                            class="delete-btn"
                            @click="resumeStore.removeEducation(index)"
                            v-if="resumeStore.educationList.length > 1"
                          />
                        </el-col>
                      </el-row>
                    </el-form>
                  </div>
                  <el-button 
                    type="primary" 
                    size="small" 
                    class="add-btn"
                    @click="resumeStore.addEducation"
                  >
                    + 添加教育经历
                  </el-button>
                </div>
              </el-tab-pane>

               <!-- 工作经验 -->
               <el-tab-pane label="工作经验" name="work">
                 <div class="section-content">
                   <!-- 工作经验数量提示 -->
                   <div v-if="resumeStore.workList.length > 2" class="limit-warning">
                     <el-alert
                       title="提示"
                       type="warning"
                       :closable="false"
                       show-icon
                     >
                       <template #default>
                         <p>工作经验超过2个，PDF预览将只显示前2个。建议保留最重要的工作经验。</p>
                       </template>
                     </el-alert>
                   </div>
                   
                   <div v-for="(item, index) in resumeStore.workList" :key="index" class="work-item">
                    <el-form label-width="90px" class="resume-form">
                      <el-row :gutter="24">
                        <el-col :span="12">
                          <el-form-item label="公司" class="form-item">
                            <el-input v-model="item.company" placeholder="请输入公司名称" class="form-input" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="职位" class="form-item">
                            <el-input v-model="item.position" placeholder="请输入职位" class="form-input" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="11">
                          <el-form-item label="开始时间" class="form-item">
                            <el-date-picker 
                              v-model="item.startDate" 
                              type="month" 
                              placeholder="选择开始时间" 
                              class="form-input"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="11">
                          <el-form-item label="结束时间" class="form-item">
                            <el-date-picker 
                              v-model="item.endDate" 
                              type="month" 
                              placeholder="选择结束时间" 
                              class="form-input"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="2" class="delete-col">
                          <el-button 
                            :icon="Delete" 
                            size="small" 
                            class="delete-btn"
                            @click="resumeStore.removeWork(index)"
                            v-if="resumeStore.workList.length > 1"
                          />
                        </el-col>
                        <el-col :span="24">
                          <el-form-item label="工作描述" class="form-item">
                            <el-input 
                              v-model="item.desc" 
                              type="textarea" 
                              :rows="3" 
                              placeholder="请描述工作内容和成果" 
                              class="form-input" 
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                  </div>
                  <el-button 
                    type="primary" 
                    size="small" 
                    class="add-btn"
                    @click="resumeStore.addWork"
                  >
                    + 添加工作经验
                  </el-button>
                </div>
              </el-tab-pane>

              <!-- 技能特长 -->
              <el-tab-pane label="技能特长" name="skills">
                <div class="section-content">
                  <el-form label-width="90px" class="resume-form">
                    <el-form-item label="技能特长" class="form-item">
                      <el-input 
                        v-model="resumeStore.skillsList" 
                        type="textarea" 
                        :rows="4"
                        placeholder="请输入技能特长（如：Vue3、React、Node.js等）" 
                        class="form-input"
                      />
                    </el-form-item>
                  </el-form>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
             </el-col>
        <!-- 右侧：预览区（引用独立组件） -->
        <el-col :span="11" class="preview-column">
          <ResumePreview />
        </el-col>
     </el-row>
    </div>
  </el-main>
</template>

<script setup>
import { ref, nextTick, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { Delete, Upload } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useResumeStore } from '@/store/resumeStore'; 
import ResumePreview from '@/components/ResumePreview.vue'; 
// 引入外部样式文件
import '@/assets/style/resume/index.css';
// 引入封装的 axios instance（会自动携带 token）
import instance from '@/utils/request';
import useStore from '@/store'; 

// 状态初始化
const resumeStore = useResumeStore();
const route = useRoute(); // 必须在 setup 顶层调用
const activeTab = ref('basic');
const newSkill = ref('');
const basicFormRef = ref(null);

// 从 store 获取模板列表
const allTemplates = computed(() => resumeStore.allTemplates);

// 页面加载时从后端获取模板和简历数据
onMounted(async () => {
  console.log('=== 页面加载开始 ===');
  
  // 先加载模板
  await resumeStore.fetchTemplates();
  console.log('模板列表已加载:', allTemplates.value);
  
  // 检查是否是编辑模式（URL 中有 id 参数）
  const resumeId = route.query.id;
  const useTemplate = route.query.useTemplate;
  const createNew = route.query.createNew;
  const templateId = route.query.templateId;
  const resumeData = route.query.resumeData;
  
  console.log('URL参数 id:', resumeId);
  console.log('URL参数 useTemplate:', useTemplate);
  console.log('URL参数 createNew:', createNew);
  console.log('URL参数 templateId:', templateId);
  
  if (resumeId) {
    console.log('🔧 编辑模式，加载简历数据，ID:', resumeId);
    
    // 等待一小段时间确保模板已完全加载
    await nextTick();
    
    const success = await resumeStore.loadResumeData(parseInt(resumeId));
    if (success) {
      console.log('当前表单数据:', resumeStore.form);
      console.log('当前教育经历:', resumeStore.educationList);
      console.log('当前工作经历:', resumeStore.workList);
      console.log('当前技能列表:', resumeStore.skillsList);
    }
  } else if (useTemplate === 'true' && templateId && resumeData) {
    console.log('📋 使用分享模板模式');
    
    // 等待一小段时间确保模板已完全加载
    await nextTick();
    
    // 先清空所有数据，确保是全新的创建模式
    resumeStore.clearResumeData();
    console.log('✅ 数据已清空，准备填充分享模板数据');
    
    // 清空当前简历ID，确保进入创建模式
    resumeStore.currentResumeId = null;
    resumeStore.currentResumeName = '';
    
    // 选择指定的模板
    resumeStore.selectedTemplateId = parseInt(templateId);
    await resumeStore.loadTemplate(parseInt(templateId));
    
    // 解析并填充分享的简历数据
    try {
      const sharedData = JSON.parse(resumeData);
      console.log('📋 分享的简历数据:', sharedData);
      
      // 填充基本信息
      if (sharedData.basic_info) {
        resumeStore.form.name = sharedData.basic_info.name || '';
        resumeStore.form.gender = sharedData.basic_info.gender || '';
        resumeStore.form.phone = sharedData.basic_info.phone || '';
        resumeStore.form.email = sharedData.basic_info.email || '';
        resumeStore.form.intention = sharedData.basic_info.intention || '';
        resumeStore.form.intro = sharedData.basic_info.intro || '';
        resumeStore.form.photoUrl = sharedData.photo_url || '';
        console.log('✅ 基本信息已填充:', resumeStore.form);
      }
      
      // 填充教育经历
      if (sharedData.education_list && Array.isArray(sharedData.education_list)) {
        resumeStore.educationList = sharedData.education_list.map(edu => ({
          school: edu.school || '',
          major: edu.major || '',
          startDate: edu.startDate || '',
          endDate: edu.endDate || ''
        }));
        console.log('✅ 教育经历已填充:', resumeStore.educationList);
      }
      
      // 填充工作经历
      if (sharedData.work_list && Array.isArray(sharedData.work_list)) {
        resumeStore.workList = sharedData.work_list.map(work => ({
          company: work.company || '',
          position: work.position || '',
          startDate: work.startDate || '',
          endDate: work.endDate || '',
          desc: work.description || work.desc || '' // 兼容两种字段名
        }));
        console.log('✅ 工作经历已填充:', resumeStore.workList);
      }
      
      // 填充技能特长
      if (sharedData.skills_list) {
        resumeStore.skillsList = sharedData.skills_list;
        console.log('✅ 技能特长已填充:', resumeStore.skillsList);
      }
      
      ElMessage.success('已加载分享的简历模板，您可以在此基础上进行修改');
    } catch (error) {
      console.error('解析分享数据失败:', error);
      ElMessage.error('加载分享模板失败');
    }
  } else if (createNew === 'true' && templateId) {
    console.log('🆕 使用模板创建新简历模式');
    
    // 等待一小段时间确保模板已完全加载
    await nextTick();
    
    // 清空所有数据，进入纯创建模式
    resumeStore.clearResumeData();
    console.log('✅ 数据已清空，准备使用指定模板');
    
    // 选择指定的模板
    resumeStore.selectedTemplateId = parseInt(templateId);
    await resumeStore.loadTemplate(parseInt(templateId));
    
    ElMessage.success('已选择模板，请填写您的简历信息');
  } else {
    console.log('📝 新建模式，清空数据');
    resumeStore.clearResumeData();
  }
  
  console.log('=== 页面加载完成 ===');
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  intention: [
    { required: true, message: '请输入求职意向', trigger: 'blur' },
    { min: 5, max: 50, message: '求职意向长度在5到50个字符', trigger: 'blur' }
  ],
  intro: [
    { min: 10, max: 200, message: '个人简介长度在10到200个字符', trigger: 'blur' }
  ]
};

// 照片处理相关状态
const currentFile = ref(null);

// 照片上传逻辑
const beforeUploadPhoto = (file) => {
  console.log('开始上传照片:', file);
  
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
  const isLt5M = file.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('请上传JPG、PNG或WebP格式的照片');
    return false;
  }
  
  if (!isLt5M) {
    ElMessage.error('照片大小不能超过5MB');
    return false;
  }
  
  // 直接处理照片上传
  handlePhotoUpload(file);
  return false; // 阻止自动上传
};

// 处理照片上传
const handlePhotoUpload = (file) => {
  console.log('📸 处理照片上传:', file);
  console.log('📸 文件类型:', file.type);
  console.log('📸 文件大小:', file.size);
  
  const reader = new FileReader();
  
  reader.onload = (e) => {
    try {
      // 更新store中的照片URL（base64格式，用于预览）
      resumeStore.form.photoUrl = e.target.result;
      console.log('✅ 照片上传成功');
      console.log('✅ photoUrl长度:', resumeStore.form.photoUrl.length);
      console.log('✅ photoUrl前100字符:', resumeStore.form.photoUrl.substring(0, 100));
      
      // 强制触发响应式更新
      nextTick(() => {
        console.log('✅ nextTick后检查photoUrl:', resumeStore.form.photoUrl ? '有值' : '无值');
        console.log('✅ store中的photoUrl:', resumeStore.form.photoUrl ? '已设置' : '未设置');
      });
      
      ElMessage.success('照片上传成功');
    } catch (error) {
      console.error('❌ 照片处理失败:', error);
      ElMessage.error('照片处理失败，请重试');
    }
  };
  
  reader.onerror = (error) => {
    console.error('❌ 文件读取失败:', error);
    ElMessage.error('文件读取失败，请重试');
  };
  
  // 读取文件为base64
  console.log('📸 开始读取文件为base64...');
  reader.readAsDataURL(file);
};

// 删除照片
const removePhoto = () => {
  resumeStore.form.photoUrl = '';
  ElMessage.success('照片已删除');
};

// 获取照片源地址
const getPhotoSrc = (photoUrl) => {
  if (!photoUrl) return '';
  
  // 如果是base64格式，直接返回
  if (photoUrl.startsWith('data:image/')) {
    return photoUrl;
  }
  
  // 如果是 /pictures/ 开头（简历照片），添加 /public 前缀
  if (photoUrl.startsWith('/pictures/')) {
    return `http://localhost:7001/public${photoUrl}`;
  }
  
  // 如果已经有 /public 前缀，直接使用
  if (photoUrl.startsWith('/public/')) {
    return `http://localhost:7001${photoUrl}`;
  }
  
  // 其他情况直接返回
  return photoUrl;
};

// 技能添加
const handleAddSkill = () => {
  if (newSkill.value.trim()) {
    resumeStore.addSkill(newSkill.value);
    newSkill.value = '';
    console.log('技能已添加:', resumeStore.skillsList);
  }
};

// 获取模板预览样式
const getTemplatePreviewStyle = (template) => {
  return {
    backgroundColor: template.style.base.bgColor,
    borderRadius: template.style.base.borderRadius,
    boxShadow: template.style.base.boxShadow || '0 2px 8px rgba(0,0,0,0.1)',
    border: `2px solid ${template.style.base.primaryColor}20`
  };
};

// 下载PDF功能 - 直接使用实时预览样式
const downloadPDF = async () => {
  try {
    console.log('开始生成PDF');
    
    // 导入PDF生成库
    const { default: html2canvas } = await import('html2canvas');
    const { default: jsPDF } = await import('jspdf');
    
    const pdf = new jsPDF('p', 'mm', 'a4');
    
    // 获取实时预览元素
    const previewElement = document.querySelector('.preview-card');
    if (!previewElement) {
      ElMessage.error('未找到预览内容，请先填写简历信息');
      return;
    }
    
    // 创建临时容器用于渲染
    const tempContainer = document.createElement('div');
    tempContainer.style.position = 'absolute';
    tempContainer.style.left = '-9999px';
    tempContainer.style.width = '210mm';
    tempContainer.style.height = '297mm';
    tempContainer.style.backgroundColor = '#ffffff';
    document.body.appendChild(tempContainer);
    
    // 克隆预览元素
    const clonedElement = previewElement.cloneNode(true);
    clonedElement.style.width = '210mm';
    clonedElement.style.height = '297mm';
    clonedElement.style.padding = '15mm';
    clonedElement.style.boxSizing = 'border-box';
    clonedElement.style.fontSize = '12px';
    clonedElement.style.lineHeight = '1.4';
    
    tempContainer.appendChild(clonedElement);
    
    const canvas = await html2canvas(clonedElement, {
      scale: 2,
      useCORS: true,
      allowTaint: true,
      logging: false
    });
    
    const imgData = canvas.toDataURL('image/png');
    pdf.addImage(imgData, 'PNG', 0, 0, 210, 297);
    
    document.body.removeChild(tempContainer);
    
    // 生成PDF文件名
    let pdfFileName = '简历.pdf';
    if (resumeStore.currentResumeName) {
      // 如果已保存，使用简历名称
      pdfFileName = `${resumeStore.currentResumeName}.pdf`;
    } else if (resumeStore.form.name) {
      // 如果未保存但填写了姓名，生成临时名称
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      pdfFileName = `${year}${month}${day}_${hours}${minutes}${seconds}_${resumeStore.form.name}.pdf`;
    }
    
    pdf.save(pdfFileName);
    
    ElMessage.success('PDF下载成功');
    console.log('PDF下载成功，文件名：', pdfFileName);
  } catch (error) {
    console.error('PDF生成失败:', error);
    ElMessage.error('PDF生成失败，请重试');
  }
};

// 保存简历功能
const saveResume = async () => {
  try {
    // 1. 验证必填字段
    if (!resumeStore.form.name) {
      ElMessage.warning('请填写姓名');
      return;
    }
    if (!resumeStore.form.phone) {
      ElMessage.warning('请填写电话');
      return;
    }
    if (!resumeStore.form.email) {
      ElMessage.warning('请填写邮箱');
      return;
    }

    console.log('开始保存简历...');

    // 检查用户是否登录
    const store = useStore();
    if (!store.app.userId) {
      ElMessage.error('请先登录');
      return;
    }

    // 2. 准备简历数据（不需要传递user_id，后端会从JWT token中获取）
    const resumeData = {
      template_id: resumeStore.selectedTemplateId, // 直接使用数字ID
      basic_info: {
        name: resumeStore.form.name,
        phone: resumeStore.form.phone,
        email: resumeStore.form.email,
        gender: resumeStore.form.gender,
        intention: resumeStore.form.intention,
        intro: resumeStore.form.intro
      },
      education_list: resumeStore.educationList,
      work_list: resumeStore.workList,
      skills_list: resumeStore.skillsList,
      photo_url: resumeStore.form.photoUrl || '',
      status: 1 // 1-草稿
    };

    console.log('简历数据：', resumeData);

    // 3. 调用后端API（根据是否有ID判断是新建还是更新）
    let result;
    if (resumeStore.currentResumeId) {
      // 更新已有简历
      result = await instance.request({
        method: 'PUT',
        url: `/resumes/${resumeStore.currentResumeId}`,
        data: resumeData
      });
      console.log('更新结果：', result);
    } else {
      // 创建新简历
      result = await instance.request({
        method: 'POST',
        url: '/resumes',
        data: resumeData
      });
      console.log('创建结果：', result);
    }

    // 4. 处理响应（instance已经处理了响应格式，直接使用result）
    if (result.code === 0) {
      ElMessage.success(result.msg || '简历保存成功！');
      console.log('简历名称：', result.data.resume_name);
      console.log('简历ID：', result.data.id);
      
      // 保存简历ID和名称到store，用于后续更新和下载PDF
      resumeStore.currentResumeId = result.data.id;
      resumeStore.currentResumeName = result.data.resume_name;
    } else {
      ElMessage.error(result.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请检查网络或后端服务是否启动');
  }
};

// 调试用：确认allTemplates有数据（打开控制台查看）
console.log('模板列表数据：', allTemplates);
</script>